package com.kj.xuyuan.login;

import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.android.flexbox.AlignItems;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.flexbox.JustifyContent;
import com.kj.xuyuan.MainActivity;
import com.kj.xuyuan.R;
import com.kj.xuyuan.adapter.UserTagAdapter;
import com.kj.xuyuan.base.BaseActivity;
import com.kj.xuyuan.base.BaseModel;
import com.kj.xuyuan.base.Constants;
import com.kj.xuyuan.base.MyApp;
import com.kj.xuyuan.http.JsonCallback;
import com.kj.xuyuan.http.JsonNoEncryptionCallback;
import com.kj.xuyuan.http.OkGoUtil;
import com.kj.xuyuan.http.UrlConstants;
import com.kj.xuyuan.mine.EditUserInfoActivity;
import com.kj.xuyuan.model.LoginBean;
import com.kj.xuyuan.model.UploadBean;
import com.kj.xuyuan.model.UserTagBean;
import com.kj.xuyuan.pop.UniversalClickPopWindow;
import com.kj.xuyuan.util.GlideUtils;
import com.kj.xuyuan.util.LogUtils;
import com.kj.xuyuan.util.PhotoSelectSingleUtile;
import com.kj.xuyuan.util.SPUtils;
import com.kj.xuyuan.util.StringUtils;
import com.kj.xuyuan.util.ToastUtil;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.decoration.GridSpacingItemDecoration;
import com.luck.picture.lib.entity.LocalMedia;
import com.lzy.okgo.model.Response;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 注册后完善信息  3步
 */
public class EditInfoActivity extends BaseActivity {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_info_step)
    TextView tvInfoStep;
    @BindView(R.id.iv_sex_boy)
    ImageView ivSexBoy;
    @BindView(R.id.tv_sex_boy)
    TextView tvSexBoy;
    @BindView(R.id.iv_sex_girl)
    ImageView ivSexGirl;
    @BindView(R.id.tv_sex_girl)
    TextView tvSexGirl;
    @BindView(R.id.ed_name)
    EditText edName;
    @BindView(R.id.ed_age)
    EditText edAge;
    @BindView(R.id.tv_next_one)
    TextView tvNextOne;
    @BindView(R.id.cl_step_one)
    ConstraintLayout clStepOne;
    @BindView(R.id.iv_head)
    ImageView ivHead;
    @BindView(R.id.tv_before_one)
    TextView tvBeforeOne;
    @BindView(R.id.tv_next_two)
    TextView tvNextTwo;
    @BindView(R.id.cl_step_two)
    ConstraintLayout clStepTwo;
    @BindView(R.id.rv_mettle_tag)
    RecyclerView rvMettleTag;
    @BindView(R.id.rv_interest_tag)
    RecyclerView rvInterestTag;
    @BindView(R.id.tv_before_two)
    TextView tvBeforeTwo;
    @BindView(R.id.tv_next_three)
    TextView tvNextThree;
    @BindView(R.id.cl_step_three)
    ConstraintLayout clStepThree;

    private int mCurrentStep = 1;
    private List<UserTagBean.ListBean> tagData1;
    private List<UserTagBean.ListBean> tagData2;
    private UserTagAdapter adapter1;
    private UserTagAdapter adapter2;
    private String gender = "2";//0保密  1男 2女
    private String nickName;
    private String age;
    private List<LocalMedia> mSelectList = new ArrayList<>();
    private LocalMedia image;
    private String headUrl;
    private boolean isExit;
    private List<String> mettleTags;
    private List<String> interestTags;

    @Override
    protected void init(Bundle savedInstanceState) {

    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.activity_edit_info;
    }

    @Override
    protected void initView() {
        mettleTags = new ArrayList<>();
        interestTags = new ArrayList<>();
        initRecyclerView();
        getTagData();
    }

    private void getTagData() {

        OkGoUtil.postRequest(getContext(), UrlConstants.GET_TAGS, null, new JsonCallback<BaseModel<UserTagBean>>() {
            @Override
            public void onSuccess(Response<BaseModel<UserTagBean>> response) {
                if (response != null && response.body() != null) {
                    if(response.body().getCode() == 1){
                        tagData1.addAll(response.body().getData().getList());
                        tagData2.addAll(response.body().getData().getList1());
                        adapter1.notifyDataSetChanged();
                        adapter2.notifyDataSetChanged();
                    }
                }
            }

            @Override
            public void onError(Response<BaseModel<UserTagBean>> response) {
                super.onError(response);
                LogUtils.e(TAG,response.getException().getMessage());
            }
        });
    }

    private void initRecyclerView() {
        tagData1 = new ArrayList<>();
        tagData2 = new ArrayList<>();
        adapter1 = new UserTagAdapter();
        adapter2 = new UserTagAdapter();
        //标签流式布局
        FlexboxLayoutManager historyManager1 = new FlexboxLayoutManager(context);
        historyManager1.setFlexWrap(FlexWrap.WRAP); //设置是否换行
        historyManager1.setFlexDirection(FlexDirection.ROW); // 设置主轴排列方式
        historyManager1.setAlignItems(AlignItems.STRETCH);
        historyManager1.setJustifyContent(JustifyContent.FLEX_START);
        rvMettleTag.setLayoutManager(historyManager1);
        //标签流式布局
        FlexboxLayoutManager historyManager2 = new FlexboxLayoutManager(context);
        historyManager2.setFlexWrap(FlexWrap.WRAP); //设置是否换行
        historyManager2.setFlexDirection(FlexDirection.ROW); // 设置主轴排列方式
        historyManager2.setAlignItems(AlignItems.STRETCH);
        historyManager2.setJustifyContent(JustifyContent.FLEX_START);
        rvInterestTag.setLayoutManager(historyManager2);


        rvMettleTag.setAdapter(adapter1);
        rvInterestTag.setAdapter(adapter2);
        adapter1.setNewData(tagData1);
        adapter2.setNewData(tagData2);

        adapter1.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if(tagData1.get(position).isSelected()){
                    tagData1.get(position).setSelected(false);
                    mettleTags.remove(tagData1.get(position).getTitle());
                }else{
                    if(mettleTags.size() < 2){
                        mettleTags.add(tagData1.get(position).getTitle());
                        tagData1.get(position).setSelected(true);
                    }
                }
                adapter1.notifyDataSetChanged();
            }
        });

        adapter2.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if(tagData2.get(position).isSelected()){
                    tagData2.get(position).setSelected(false);
                    interestTags.remove(tagData2.get(position).getTitle());
                }else{
                    if(interestTags.size() < 2){
                        interestTags.add(tagData2.get(position).getTitle());
                        tagData2.get(position).setSelected(true);
                    }
                }
                adapter2.notifyDataSetChanged();
            }
        });
    }

    @Override
    protected void initData() {

    }

    @Override
    protected int getTitleBarType() {
        return -1;
    }

    @OnClick({R.id.iv_back, R.id.iv_sex_boy, R.id.tv_sex_boy, R.id.iv_sex_girl, R.id.tv_sex_girl, R.id.tv_next_one, R.id.iv_head, R.id.tv_before_one, R.id.tv_next_two, R.id.tv_before_two, R.id.tv_next_three})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                if(mCurrentStep == 1){//在编辑资料第一步,不显示，无操作

                }else{
                    mCurrentStep --;
                    changeView();
                }
                break;
            case R.id.iv_sex_boy:
            case R.id.tv_sex_boy:
                if(!gender.equals("1")){
                    gender = "1";
                    changeSexView();
                }
                break;
            case R.id.iv_sex_girl:
            case R.id.tv_sex_girl:
                if(!gender.equals("2")){
                    gender = "2";
                    changeSexView();
                }
                break;
            case R.id.tv_next_one:
                nickName = edName.getText().toString().trim();
                age = edAge.getText().toString().trim();
                if(StringUtils.isEmpty(nickName)){
                    ToastUtil.showToast(context,"昵称未填写");
                    return;
                }
                if(StringUtils.isEmpty(age)){
                    ToastUtil.showToast(context,"年龄未填写");
                    return;
                }
                mCurrentStep = 2;
                changeView();
                break;
            case R.id.iv_head:
                popGetImageMethodWindow();
                break;
            case R.id.tv_before_one:
                mCurrentStep = 1;
                changeView();
                break;
            case R.id.tv_next_two:
                break;
            case R.id.tv_before_two:
                mCurrentStep = 2;
                changeView();
                break;
            case R.id.tv_next_three:
                checkData();
                break;
        }
    }

    private void checkData() {
        StringBuffer sb = new StringBuffer();
        for(int i = 0;i<mettleTags.size();i++){
            sb.append(mettleTags.get(i)).append(",");
        }
        for(int i = 0;i<interestTags.size();i++){
            sb.append(interestTags.get(i)).append(",");
        }
        if(sb.length() == 0){
            ToastUtil.showToast(context,"未选择标签");
            return;
        }

        sb.deleteCharAt(sb.length()-1);

        Map map = new HashMap();
        map.put("nickname",nickName);
        map.put("years",age);
        map.put("tags",sb.toString());
        map.put("avatar",headUrl);
        map.put("gender",gender);

        OkGoUtil.postRequest(getContext(), UrlConstants.INIT_USER_DATA, map, new JsonCallback<BaseModel<?>>() {
            @Override
            public void onSuccess(Response<BaseModel<?>> response) {
                if (response != null && response.body() != null) {
                    if(response.body().getCode() == 1){
                        SPUtils.setStringData(context, Constants.AVATAR,headUrl);
                        SPUtils.setBooleanData(context, Constants.IS_LOGIN,true);
                        startActivity(MainActivity.class);
                        finish();
                    }
                }
            }

            @Override
            public void onError(Response<BaseModel<?>> response) {
                super.onError(response);
                LogUtils.e(TAG,response.getException().getMessage());
            }
        });
    }

    private void popGetImageMethodWindow() {
        List<String> data = new ArrayList<>();
        data.add("拍摄");
        data.add("从相册选择");
        UniversalClickPopWindow popWindow = new UniversalClickPopWindow(context,data);
        popWindow.showAtLocation(getWindow().getDecorView(), Gravity.BOTTOM,0,0);
        popWindow.setAnimationStyle(R.style.popwindow_center_anim_style);
        popWindow.setItemClickListener(new UniversalClickPopWindow.ItemClickListener() {
            @Override
            public void click(int position) {
                if(position == 0)
                    PhotoSelectSingleUtile.cameraPhoto(context, PictureMimeType.ofImage());
                else
                    PhotoSelectSingleUtile.selectPhoto(context, PictureMimeType.ofImage(),mSelectList, 1);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    List<LocalMedia> localMedia = PictureSelector.obtainMultipleResult(data);
                    if(localMedia.size() == 0){
                        return;
                    }
                    mSelectList.clear();
                    image = localMedia.get(0);
                    uploadImage();
                    break;
            }
        }
    }

    private void uploadImage() {
        showDialog();
        File file = new File(MyApp.selectPhotoShow(context,image));
        OkGoUtil.postSingleFile(context, UrlConstants.UPLOAD,file,new JsonNoEncryptionCallback<BaseModel<UploadBean>>() {
            @Override
            public void onSuccess(Response<BaseModel<UploadBean>> response) {
                if (response != null && response.body() != null) {
                    if(response.body().getCode() == 1){
                        headUrl = response.body().getData().getUrl();
                        GlideUtils.loadCircleImage(context,UrlConstants.Base_Http+headUrl,ivHead);
                        mCurrentStep = 3;
                        changeView();
                    }
                    ToastUtil.showToast(context,response.body().getMsg());
                    dismissDialog();
                }
            }

            @Override
            public void onError(Response<BaseModel<UploadBean>> response) {
                super.onError(response);
                dismissDialog();
                LogUtils.e(TAG,"response ="+response.getException());
            }
        });
    }

    private void changeSexView() {
        switch (gender){
            case "1"://男
                tvSexBoy.setTextColor(getResources().getColor(R.color.pink));
                ivSexBoy.setImageResource(R.mipmap.icon_boy_pink);
                tvSexGirl.setTextColor(getResources().getColor(R.color.gray9));
                ivSexGirl.setImageResource(R.mipmap.icon_girl_gray);
                break;
            case "2"://女
                tvSexBoy.setTextColor(getResources().getColor(R.color.gray9));
                ivSexBoy.setImageResource(R.mipmap.icon_boy_gray);
                tvSexGirl.setTextColor(getResources().getColor(R.color.pink));
                ivSexGirl.setImageResource(R.mipmap.icon_girl_pink);
                break;
        }
    }

    private void changeView() {
        tvInfoStep.setText("完善信息 "+mCurrentStep+"/3");
        switch (mCurrentStep){
            case 1:
                clStepOne.setVisibility(View.VISIBLE);
                clStepTwo.setVisibility(View.GONE);
                clStepThree.setVisibility(View.GONE);
                ivBack.setVisibility(View.GONE);

                break;
            case 2:
                clStepOne.setVisibility(View.GONE);
                clStepTwo.setVisibility(View.VISIBLE);
                clStepThree.setVisibility(View.GONE);
                ivBack.setVisibility(View.VISIBLE);
                break;
            case 3:
                clStepOne.setVisibility(View.GONE);
                clStepTwo.setVisibility(View.GONE);
                clStepThree.setVisibility(View.VISIBLE);
                ivBack.setVisibility(View.VISIBLE);
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if(mCurrentStep == 1){
                exitByDoubleClick();
            }else{
                mCurrentStep--;
                changeView();
            }
        }
        return false;
    }

    //双击返回退出
    private void exitByDoubleClick() {
        Timer tExit = null;
        if (!isExit) {
            isExit = true;
            Toast.makeText(this, "再返回一次退出程序", Toast.LENGTH_SHORT).show();
            tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false;//取消退出
                }
            }, 2000);// 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务
        } else {
            finish();
            System.exit(0);
        }
    }
}